package cn.liulin.java8.stream;

import cn.liulin.java8.pojo.Dish;
import com.alibaba.fastjson.JSON;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * cn.liulin.java8.stream$
 *
 * @author ll
 * @date 2021-10-15 16:34:01
 **/
public class PartitionStream {
    public static void main(String[] args) {
        Dish dish1 = new Dish("hasd", true);
        Dish dish2 = new Dish("g", false);
        Dish dish3 = new Dish("asdf", false);
        Dish dish4 = new Dish("dfg", true);
        List<Dish> menu = Arrays.asList(dish1, dish2, dish3, dish4);
//        partitionOne(menu);
//        partitionTwo(menu);
//        partitionThree(menu);
        partitionFour(100);

    }

    /**
     * 求n以内的质数
     * @author ll
     * @date 2021-10-15 17:24:07
     * @param n
     * @return void
     **/
    private static void partitionFour(int n) {
        Map<Boolean, List<Integer>> collect = IntStream.rangeClosed(2, n)
                .boxed()
                .collect(
                        Collectors.partitioningBy(candidate -> isPrime(candidate))
                );
        System.out.println(JSON.toJSONString(collect));
    }

    private static void partitionThree(List<Dish> menu) {
        Map<Boolean, Dish> collect = menu.stream()
                .collect(
                        Collectors.partitioningBy(Dish::isVegetarian, Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparingInt(Dish::getCalories)), Optional::get))
                );
        System.out.println(JSON.toJSONString(collect));
    }

    public static boolean isPrime(int n) {
        return IntStream.range(2, n)
                .boxed()
                .noneMatch(i -> n % i == 0);
    }

    private static void partitionTwo(List<Dish> menu) {
        Map<Boolean, Map<String, List<Dish>>> collect = menu.stream()
                .collect(
                        Collectors.partitioningBy(Dish::isVegetarian, Collectors.groupingBy(Dish::getName))
                );
        System.out.println(JSON.toJSONString(collect));
    }

    private static void partitionOne(List<Dish> menu) {
        Map<Boolean, List<Dish>> collect = menu.stream()
                .collect(
                        Collectors.partitioningBy(Dish::isVegetarian)
                );
        System.out.println(JSON.toJSONString(collect));
    }
}
